<?php

/**
 * SigmaCMS - Content Management System
 *
 * Copyright (C) 2008 Pavol Biely
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 * @package    SigmaCMS
 * @author     Pavol Biely <pavolbiely@gmail.com>
 * @copyright  2008 Pavol Biely
 * @license    http://www.gnu.org/licenses/gpl.txt   GNU General Public License
 * @link       http://pabi3.com/
 * @since      0.1.0
 */

final class Admin_Members
{
	/**
	 * Initialization
	 *
	 * @return void
	 */
	public function initialize()
	{
		Admin::header(_ADMIN_MEMBERS);

		echo "<h1>"._ADMIN_MEMBERS."</h1>";

		// specific group?
		$group = NULL;
		if (isset($_GET['group'])) {
			$group = "WHERE `group_id`=".intval(_get('group'));
		}

		// load members
		$sql = db::query("SELECT `username`,`group_id`,`blocked` FROM ".db::prefix('members')." $group ORDER BY `group_id`,`username`");
		if (db::numRows($sql) > 0) {
			echo "<table>\n";
			echo "<tr>\n";
			echo "<th>"._ADMIN_MEMBERS_USERNAME."</th>\n";
			echo "<th>"._ADMIN_MEMBERS_GROUP."</th>\n";
			echo "<th>"._ADMIN_MEMBERS_STATUS."</th>\n";
			echo "<th>"._ADMIN_ACTIONS."</th>\n";
			echo "</tr>\n";

			// print members
			while ($row = db::fetchObject($sql)) {
				// admin's account will not be displayed in this list
				if ($row->username == 'admin') {
					// admin's account
					echo "<tr class='disabled'>\n";
					echo "<td>admin <small>("._ADMIN_MEMBER.")</small></td>\n";
					echo "<td class='center'>".$this->getGroupNameById(1)."</td>\n";
					echo "<td class='center'>".Admin::image('member_admin',_ADMIN_MEMBERS_ADMIN)."</td>\n";
					echo "<td class='center'>\n";
					if (Member::getUsername() == 'admin') {
						echo "<a href='index.php?action=members&amp;page=edit&amp;username=admin'>".Admin::image('member_edit',_ADMIN_MEMBERS_EDIT)."</a>\n";
					} else {
						echo "-";
					}
					echo "</td>\n";
					echo "</tr>\n";
				} else {
					echo "<tr>\n";
					echo "<td width='50%'>".$row->username."</td>\n";
					echo "<td width='20%' class='center'>".$this->getGroupNameById($row->group_id)."</td>\n";
					echo "<td width='15%' class='center'><a href='index.php?action=members&amp;page=block&amp;username=".$row->username."'>".($row->blocked ? Admin::image('member_blocked',_ADMIN_MEMBERS_BLOCKED) : Admin::image('member_unblocked',_ADMIN_MEMBERS_UNBLOCKED))."</a></td>\n";
					echo "<td width='15%' class='center'>\n";
					echo "<a href='index.php?action=members&amp;page=edit&amp;username=".$row->username."'>".Admin::image('member_edit',_ADMIN_MEMBERS_EDIT)."</a>\n";
					echo "<a href='index.php?action=members&amp;page=delete&amp;username=".$row->username."'>".Admin::image('member_delete',_ADMIN_MEMBERS_DELETE)."</a>\n";
					echo "</td>\n";
					echo "</tr>\n";
				}
			}
			echo "</table>\n";
		} else {
			echo "<p>"._ADMIN_MEMBERS_NO."</p>\n";
		}
		db::free($sql);

		Admin::footer();
	}

	/**
	 * Menu
	 *
	 * @return void
	 */
	public function menu()
	{
		echo "<h2>"._ADMIN_MEMBERS."</h2>\n";
		echo "<ul>\n";
		echo "<li><a href='index.php?action=members&amp;page=add' title='"._ADMIN_MEMBERS_ADD."'>"._ADMIN_MEMBERS_ADD."</a></li>\n";
		echo "<li><a href='index.php?action=members&amp;page=addgroup' title='"._ADMIN_MEMBERS_GROUP_ADD."'>"._ADMIN_MEMBERS_GROUP_ADD."</a></li>\n";
		echo "<li><a href='index.php?action=members&amp;page=grouplist' title='"._ADMIN_MEMBERS_GROUP_LIST."'>"._ADMIN_MEMBERS_GROUP_LIST."</a></li>\n";
		echo "</ul>\n";
	}

	/**
	 * Return name of the group by its ID
	 *
	 * @param integer $id
	 * @return string
	 */
	private function getGroupNameById($id)
	{
	    $groupname = db::fQuery("SELECT `name` FROM ".db::prefix('members_groups')." WHERE `id`='".intval($id)."' LIMIT 1");
	    if (!$groupname) {
	    	return _ADMIN_MEMBERS_GROUP_UNKNOWN; // without group
	    }
	    return $groupname;
	}

	/**
	 * Return the number of members in group specified by ID
	 *
	 * @param integer $id
	 * @return integer
	 */
	private function countGroupMembersById($id)
	{
		// select members
		$sql = db::query("SELECT `username` FROM ".db::prefix('members')." WHERE `group_id`='".intval($id)."'");

		return db::numRows($sql);
	}

	/**
	 * Return array containing restricted sections of administration
	 *
	 * @param integer $group
	 * @return array
	 */
	private function getRestrictedSections($group = 0)
	{
		$sections = array();
		
		if ($group == 0) {
			$scanSections = scandir('./actions/');
			
			// skip . and ..
			$scanSections = array_slice($scanSections,2);
			
			// remove sections, which cannot be blocked
			for ($i = 0; $i < count($scanSections); $i++) {
				$regexp = str_replace('.','\\.',cfg::ADMIN_PREFIX);
				if (preg_match("/^$regexp([a-zA-Z]+)\.php$/",$scanSections[$i],$matches)) {
					if (!in_array($matches[1],Admin::getAllowedSections())) {
						$sections[] = $matches[1];
					}
				}
			}
		} else {
			$sql = db::query("SELECT `section` FROM ".db::prefix('members_sections')." WHERE `group_id`='".intval($group)."'");
			while ($row = db::fetchObject($sql)) {
				if (in_array($row->section,$this->getRestrictedSections())) {
				$sections[] = $row->section;
				}
			}
			db::free($sql);
		}
		
		return $sections;
	}

	/**
	 * (Un)block member
	 *
	 * @return void
	 */
	public function page_block()
	{
		$username = _get('username');

		if (Member::isValidUsername($username)) {
			// blocation status
			$blocked  = db::fQuery("SELECT `blocked` FROM ".db::prefix('members')." WHERE `username`='".db::escape($username)."' AND `username`!='admin'");
	
			// does the member exist?
			if ($blocked !== false) {
				// (un)block member account
				if ($blocked == 1) {
					db::query("UPDATE ".db::prefix('members')." SET `blocked`='0' WHERE `username`='".db::escape($username)."'");
					Actionlog::add(sprintf(_LOG_ADMIN_MEMBER_BLOCK_OFF,$username));
				} else {
					db::query("UPDATE ".db::prefix('members')." SET `blocked`='1' WHERE `username`='".db::escape($username)."'");
					Actionlog::add(sprintf(_LOG_ADMIN_MEMBER_BLOCK_ON,$username));
				}
			}
		}

		Admin::redirect('index.php?action=members');
	}

	/**
	 * Add member
	 *
	 * @return void
	 */
	public function page_add()
	{
		Admin::header(_ADMIN_MEMBERS_ADD);
		
		echo "<h2>"._ADMIN_MEMBERS_ADD."</h2>\n";
		
		if (isset($_POST['submit'])) {
			// error reports
			$error = array();

			$username = _post('username');

			if (!Member::isValidUsername($username)) {
				$username = false;
				$error[] = _ADMIN_MEMBERS_USERNAME_ERROR;
			}
			
			$password = _post('password');
			if (strlen($password) <= 4) {
				$password = false;
				$error[] = _ADMIN_MEMBERS_PASSWORD_ERROR;
			} else {
				$password = hash('sha512',$password.$username);
			}

			$group = intval(_post('group'));
			if (false === db::fQuery("SELECT `id` FROM ".db::prefix('members_groups')." WHERE `id`=".$group)) {
				$group = false;
			}

			$block = _post('block') ? '1' : '0';

			if ($username && $password && $group) {
				// insert new member into database
				db::query(
				"INSERT INTO ".db::prefix('members')."(`username`,`password`,`group_id`,`blocked`) VALUES ("
				."'".db::escape($username)."',"
				."'".db::escape($password)."',"
				."'".db::escape($group)."',"
				."'".db::escape($block)."'"
				.")"
				);

				Actionlog::add(sprintf(_LOG_ADMIN_MEMBER_ADD, $username));

				Admin::addEvent('memberAdd', $username);

				Admin::redirect('index.php?action=members');
			} else {
				foreach ($error as $key => $value) {
					echo "<p class='red'>$value</p>";
				}
			}
		}
		
		echo "<form action='index.php?action=members&amp;page=add' method='post'>\n";
		echo "<fieldset>\n";
		
		echo "<label for='username'>"._ADMIN_MEMBERS_USERNAME." <small>[a-zA-Z0-9_-]{4,20}</small></label>\n";
		echo "<input id='username' name='username' type='text' value='"._hsc(_post('username'))."' />\n";
		
		echo "<label for='password'>"._ADMIN_MEMBERS_PASSWORD." <small>.{5,}</small></label>\n";
		echo "<input id='password' name='password' type='text' />\n";
		
		echo "<label for='group'>"._ADMIN_MEMBERS_GROUP."</label>\n";
		echo "<select id='group' name='group'>\n";
		$sql = db::query("SELECT `id`,`name` FROM ".db::prefix('members_groups')." ORDER BY `id` ASC");
		while ($row = db::fetchObject($sql)) {
			echo "<option value='".$row->id."'".($row->id == _post('group') ? " selected='selected'" : NULL).">".$row->name."</option>\n";
		}
		db::free($sql);
		echo "</select>\n";
		
		echo "<label for='block'>"._ADMIN_MEMBERS_BLOCK."</label>\n";
		echo "<input id='block' name='block' type='checkbox' value='1'".(isset($_POST['block']) ? " checked='checked'" : NULL)." />\n";
		
		echo "<p class='center'>\n";
		echo "<input name='submit' type='submit' value='"._ADMIN_ADD."' />\n";
		echo "</p>\n";
		
		echo "</fieldset>\n";
		echo "</form>\n";
		
		Admin::footer();
	}

	/**
	 * Edit member
	 *
	 * @return void
	 */
	public function page_edit()
	{
		// username must be set
		if (!isset($_GET['username']) || !Member::isValidUsername(_get('username'))) {
			Admin::redirect('index.php?action=members');
		}

		$username = _get('username');

		Admin::header(_ADMIN_MEMBERS_EDIT,$username);

		echo "<h2>"._ADMIN_MEMBERS_EDIT." - $username</h2>\n";

		// admin's password can be changed only by himself
		if (Member::getUsername() != 'admin' && $username == 'admin') {
			Admin::redirect('index.php?action=members');
		}

		// actual password required
		$actualRequired = false;
		if ((Member::getUsername() == 'admin' && $username == 'admin') || Member::getUsername() != 'admin') {
			$actualRequired = true;
		}

		if (isset($_POST['submit'])) {
			// error reporting
			$error = array();

			// current password
			$actual = hash('sha512',_post('actual').$username);

			// new password
			$first  = _post('first');

			// new password (again)
			$second = _post('second');

			// is password going to be changed?
			$changePassword = true;
			if (empty($actual) || empty($first)) {
				$changePassword = false;
			}

			// group ID
			$group = intval(_post('group'));
			if (false === db::fQuery("SELECT `id` FROM ".db::prefix('members_groups')." WHERE `id`=".$group)) {
				$error[] = _ADMIN_MEMBERS_GROUP_UNKNOWN;
			}

			// password must be longer than 4 characters
			if ($changePassword) {
				if (strlen($first) <= 4) {
					$error[] = _ADMIN_MEMBERS_PASSWORD_ERROR;
				} else if ($actualRequired && $actual !== db::fQuery("SELECT `password` FROM ".db::prefix('members')." WHERE `username`='".db::escape($username)."'")) {
					$error[] = _ADMIN_MEMBERS_PASSWORD_ACTUAL_ERROR;
				} else if ($first !== $second) {
					$error[] = _ADMIN_MEMBERS_CHANGE_PASSWORD_DIFFERENT;
				}
			}

			if (count($error) == 0) {
				// success even without any actions
				$sql = true;

				// it is allowed to update the password
				if ($changePassword) {
					// encrypt new password by SHA-512
					$password = hash('sha512',$first.$username);

					// update password
					$sql = db::query("UPDATE ".db::prefix('members')." SET `password`='".db::escape($password)."' WHERE `username`='".db::escape($username)."'");
				}

				// update group
				if ($username != 'admin') {
					$sql = db::query("UPDATE ".db::prefix('members')." SET `group_id`='".intval($group)."' WHERE `username`='".db::escape($username)."'");
				}

				// success?
				if ($sql) {
					Actionlog::add(sprintf(_LOG_ADMIN_MEMBER_EDIT, $username));
					Admin::addEvent('memberEdit', $username);
					Admin::redirect('index.php?action=members');
				} else {
					echo "<p class='red'>"._ADMIN_MEMBERS_CHANGE_PASSWORD_ERROR."</p>\n";
				}
			} else {
				foreach ($error as $key => $value) {
					echo "<p class='red'>$value</p>\n";
				}
			}
		}

		$sql = db::query("SELECT `group_id` FROM ".db::prefix('members')." WHERE `username`='".db::escape($username)."'");
		$row = db::fetchObject($sql);
		if (db::numRows($sql) == 0) {
			echo "<p class='red'>".sprintf(_ADMIN_MEMBERS_NOT_FOUND, $username)."</p>\n";
			Admin::footer();
			exit;
		}

	    echo "<form action='index.php?action=members&amp;page=edit&amp;username=$username' method='post'>\n";
	    echo "<fieldset>\n";

	    echo "<h3>"._ADMIN_MEMBERS_CHANGE_PASSWORD."</h3>\n";
	    if ($actualRequired) {
    		echo "<label for='actual'>"._ADMIN_MEMBERS_CHANGE_PASSWORD_ORIGINAL."</label>\n";
    		echo "<input id='actual' name='actual' type='password' />\n";
	    }

	    echo "<label for='first'>"._ADMIN_MEMBERS_CHANGE_PASSWORD_FIRST."</label>\n";
	    echo "<input id='first' name='first' type='password' />\n";

	    echo "<label for='second'>"._ADMIN_MEMBERS_CHANGE_PASSWORD_SECOND."</label>\n";
	    echo "<input id='second' name='second' type='password' />\n";

	    /*$blocked = db::fQuery("SELECT `blocked` FROM ".db::prefix('members')." WHERE `username`='".db::escape($username)."'");
	    echo "<label for='block'>"._ADMIN_MEMBERS_BLOCK."</label>\n";
	    echo "<input id='block' name='block' type='checkbox' ".($blocked ? "checked='checked'" : NULL)." />\n";*/

	    if ($username != 'admin') {
		    echo "<h3>"._ADMIN_MEMBERS_CHANGE_GROUP."</h3>\n";
		    echo "<label for='group'>"._ADMIN_MEMBERS_GROUP."</label>\n";
		    echo "<select name='group'>\n";
		    $sql2 = db::query("SELECT `id`,`name` FROM ".db::prefix('members_groups')." ORDER BY `name` ASC");
		    while ($row2 = db::fetchObject($sql2)) {
		    	echo "<option value='".$row2->id."'".($row->group_id == $row2->id ? " selected='selected'" : NULL).">".$row2->name."</option>\n";
		    }
		    db::free($sql2);
		    echo "</select>\n";
	    } else {
	    	echo "<input name='group' type='hidden' value='1' />\n";
	    }

	    echo "<p class='center'>\n";
	    echo "<input name='submit' type='submit' value='"._ADMIN_EDIT."' />\n";
	    echo "</p>\n";

	    echo "</fieldset>\n";
	    echo "</form>\n";

	    db::free($sql);

	    Admin::footer();
	}

	/**
	 * Delete member
	 *
	 * @return void
	 */
	public function page_delete()
	{
		// username must be set
		if (!isset($_GET['username']) || !Member::isValidUsername(_get('username'))) {
			Admin::redirect('index.php?action=members');
		}

		Admin::header(_ADMIN_MEMBERS_DELETE);

		$username = _get('username');

		if (_get('sure') == 1) {
			// delete member from database; member's username must not "admin"
			if ($username != 'admin') {
				// get member id
				$memberId = db::fQuery("SELECT `id` FROM ".db::prefix('members')." WHERE `username`='".db::escape($username)."' LIMIT 1");
				
				// delete member
				db::query("DELETE FROM ".db::prefix('members')." WHERE `id`='".db::escape($memberId)."' LIMIT 1");
				
				// delete member's session
				db::query("DELETE FROM ".db::prefix('members_sessions')." WHERE `memberid`='".db::escape($memberId)."' LIMIT 1");
				
				Actionlog::add(sprintf(_LOG_ADMIN_MEMBER_DELETE,$username));

				Admin::addEvent('memberDelete',$username);
			}

			Admin::redirect('index.php?action=members');
		} else {
			Admin::confirm('index.php?action=members&page=delete&username='.$username.'&sure=1');
		}

		Admin::footer();
	}

	/**
	 * Add group
	 *
	 * @return void
	 */
	public function page_addgroup()
	{
	    Admin::header(_ADMIN_MEMBERS_GROUP_ADD);

	    echo "<h2>"._ADMIN_MEMBERS_GROUP_ADD."</h2>\n";

	    if (isset($_POST['submit'])) {
	    	// error reports
	    	$error = array();

	        // group name
	        $groupname = trim(_hsc(_post('groupname')));
	        if (strlen($groupname) < 3) {
	        	$error[] = _ADMIN_MEMBERS_GROUP_ADD_ERROR_NAME;
	        }

	        // sections
	        $sectionPost = (array) _post('section');
	        $section     = array();
	        foreach ($sectionPost as $key => $value) {
	            if (preg_match('/^plugin\./', $value) || in_array($value, $this->getRestrictedSections())) {
	            	$section[] = $value;
	            }
	        }

	        // no error occurred?
	        if (count($error) == 0) {
		        // insert new group into database
		        $sql = db::query("INSERT INTO ".db::prefix('members_groups')." (`name`) VALUES('".db::escape($groupname)."')");
	
		        // get the last inserted ID
		        $lid = db::lastId();
	
		        // success?
		    	if ($sql) {
					Actionlog::add(sprintf(_LOG_ADMIN_MEMBER_GROUP_ADD, $groupname));
	
		    	    // add access to single sections
	                foreach ($section as $key) {
	                    db::query("INSERT INTO ".db::prefix('members_sections')."(`group_id`,`section`) VALUES('".intval($lid)."','".db::escape($key)."')");
	                }

		    		Admin::redirect('index.php?action=members&page=grouplist');
		    	} else {
		    	    echo "<p class='red'>"._ADMIN_MEMBERS_GROUP_ADD_ERROR."</p>\n";
		    	}
	        } else {
	        	foreach ($error as $key => $value) {
	        		echo "<p class='red'>$value</p>\n";
	        	}
	        }
	    }

	    echo "<form action='index.php?action=members&amp;page=addgroup' method='post'>\n";
	    echo "<fieldset>\n";

	    echo "<label for='groupname'>"._ADMIN_MEMBERS_GROUP."</label>\n";
	    echo "<input id='groupname' name='groupname' type='text' value='"._hsc(_post('groupname'))."' />\n";

	    echo "<label>"._ADMIN_MEMBERS_SECTIONS."</label>\n";
	    $sections = $this->getRestrictedSections();
	    foreach ($sections as $key) {
	    	$checked = NULL;
	    	if (in_array($key, (array) _post('section'))) {
	    		$checked = " checked='checked'";
	    	}

	        $constant = strtoupper('_ADMIN_'.$key);
	        if (defined($constant)) {
	        	echo "<input name='section[]' type='checkbox' value='$key'$checked /> ".constant($constant)."\n";
	        } else {
                echo "<input name='section[]' type='checkbox' value='$key'$checked /> $key\n";
	        }
	        echo "<br />\n";
	    }

	    // plugins
	    $sections = Plugin::getPlugins();

	    // are there any plugins installed?
	    if (count($sections) > 0) {
		    echo "<label>"._ADMIN_PLUGINS."</label>\n";
		    foreach ($sections as $key => $plugin) {
		    	$checked = NULL;
		    	if (in_array('plugin.'.$key, (array) _post('section'))) {
		    		$checked = " checked='checked'";
		    	}
	            echo "<input name='section[]' type='checkbox' value='plugin.$key'$checked /> ".$plugin->name()."\n";
		        echo "<br />\n";
		    }
	    }

	    echo "<p class='center'>\n";
	    echo "<input name='submit' type='submit' value='"._ADMIN_ADD."' />\n";
	    echo "</p>\n";

	    echo "</fieldset>\n";
	    echo "</form>\n";

	    Admin::footer();
	}

	/**
	 * Edit group
	 *
	 * @return void
	 */
	public function page_editgroup()
	{
		Admin::header(_ADMIN_MEMBERS_GROUP_EDIT);
		
		echo "<h2>"._ADMIN_MEMBERS_GROUP_EDIT."</h2>\n";
		
		if (_get('id') == 1) {
			echo "<p class='red'>"._ADMIN_MEMBERS_GROUP_EDIT_ADMIN."</p>\n";
			Admin::footer();
			exit;
		}
		
		if (isset($_POST['submit'])) {
			// error reports
			$error = array();

			// group name
			$groupname = trim(_hsc(_post('groupname')));
			if (strlen($groupname) < 3) {
				$error[] = _ADMIN_MEMBERS_GROUP_EDIT_ERROR_NAME;
			}
		
			// sections
			$sectionPost = (array) _post('section');
			$section = array();
			foreach ($sectionPost as $key => $value) {
				if (preg_match('/^plugin\./',$value) || in_array($value, $this->getRestrictedSections())) {
					$section[] = $value;
				}
			}

			// update group name
			$sql = db::query("UPDATE ".db::prefix('members_groups')." SET `name`='".db::escape($groupname)."' WHERE `id`='".intval(_get('id'))."'");
			if (count($error) == 0) {
				// success?
				if ($sql) {
					Actionlog::add(sprintf(_LOG_ADMIN_MEMBER_GROUP_EDIT, $groupname));

					// delete present access rights to this section for this group
					db::query("DELETE FROM ".db::prefix('members_sections')." WHERE `group_id`='".intval(_get('id'))."'");

					// add access to single sections
					foreach ($section as $key) {
						db::query("INSERT INTO ".db::prefix('members_sections')."(`group_id`,`section`) VALUES('".intval(_get('id'))."','".db::escape($key)."')");
					}

					Admin::redirect('index.php?action=members&page=grouplist');
				} else {
					echo "<p class='red'>"._ADMIN_MEMBERS_GROUP_EDIT_ERROR."</p>\n";
				}
			} else {
				foreach ($error as $key => $value) {
					echo "<p class='red'>$value</p>\n";
				}
			}
		}
		
		echo "<form action='index.php?action=members&amp;page=editgroup&amp;id=".intval(_get('id'))."' method='post'>\n";
		echo "<fieldset>\n";
		
		echo "<label for='groupname'>"._ADMIN_MEMBERS_GROUP."</label>\n";
		echo "<input id='groupname' name='groupname' type='text' value='".$this->getGroupNameById(_get('id'))."' />\n";
		
		echo "<label>"._ADMIN_MEMBERS_SECTIONS."</label>\n";
		$sections = $this->getRestrictedSections();
		foreach ($sections as $key) {
			$checked = NULL;
			if (in_array($key, (array) _post('section')) || in_array($key, $this->getRestrictedSections(_get('id')))) {
				$checked = " checked='checked'";
			}
			
			$constant = strtoupper('_ADMIN_'.$key);
			if (defined($constant)) {
				echo "<input name='section[]' type='checkbox' value='$key'$checked /> ".constant($constant)."\n";
			} else {
				echo "<input name='section[]' type='checkbox' value='$key'$checked /> $key\n";
			}
			echo "<br />\n";
		}
		
		// plugins
		$sections = Plugin::getPlugins();
		
		// are there any registered plugins?
		if (count($sections) > 0) {
			echo "<label>"._ADMIN_PLUGINS."</label>\n";
			foreach ($sections as $key => $plugin) {
				$checked = NULL;
				if (in_array('plugin.'.$key, (array) _post('section')) || false !== db::fQuery("SELECT `section` FROM ".db::prefix('members_sections')." WHERE `section`='".db::escape('plugin.'.$key)."' AND `group_id`='".intval(_get('id'))."' LIMIT 1")) {
					$checked = "checked='checked'";
				}
				echo "<input name='section[]' type='checkbox' value='plugin.$key' $checked /> ".$plugin->name()."\n";
				echo "<br />\n";
			}
		}
		
		echo "<p class='center'>\n";
		echo "<input name='submit' type='submit' value='"._ADMIN_EDIT."' />\n";
		echo "</p>\n";
		
		echo "</fieldset>\n";
		echo "</form>\n";
		
		Admin::footer();
	}

	/**
	 * Delete group
	 *
	 * @return void
	 */
	public function page_deletegroup()
	{
		if (!isset($_GET['id'])) {
			Admin::redirect('index.php?action=members&page=grouplist');
		}

		Admin::header(_ADMIN_MEMBERS_GROUP_DELETE);
		
		if (_get('id') == 1) {
			echo "<p class='red'>"._ADMIN_MEMBERS_GROUP_DELETE_ADMIN."</p>";
			Admin::footer();
			exit;
		}
		
		// members ID
		$id = intval(_get('id'));
		
		// is this group empty?
		if ($this->countGroupMembersById($id) > 0) {
			echo "<h2>"._ADMIN_MEMBERS_GROUP_DELETE."</h2>\n";
			echo "<p class='red'>"._ADMIN_MEMBERS_GROUP_DELETE_ERROR."</p>\n";
		} else if (_get('sure') == 1) {
			// group name
			$groupName = db::fQuery("SELECT `name` FROM ".db::prefix('members_groups')." WHERE `id`='".db::escape($id)."' LIMIT 1");

			// delete group
			db::query("DELETE FROM ".db::prefix('members_groups')." WHERE `id`='".db::escape($id)."' LIMIT 1");

			// delete sections which belongs to this group
			db::query("DELETE FROM ".db::prefix('members_sections')." WHERE `group_id`='".db::escape($id)."'");

			Actionlog::add(sprintf(_LOG_ADMIN_MEMBER_GROUP_DELETE,$groupName));

			Admin::redirect('index.php?action=members&page=grouplist');
		} else {
			Admin::confirm('index.php?action=members&page=deletegroup&id='.$id.'&sure=1');
		}

		Admin::footer();
	}

	/**
	 * Group list
	 *
	 * @return void
	 */
	public function page_grouplist()
	{
		Admin::header(_ADMIN_MEMBERS_GROUP_LIST);

		echo "<h2>"._ADMIN_MEMBERS_GROUP_LIST."</h2>\n";

		$sql = db::query("SELECT `id`,`name` FROM ".db::prefix('members_groups')." ORDER BY `name` ASC");
		echo "<table>\n";
		echo "<tr>\n";
		echo "<th>"._ADMIN_MEMBERS_GROUP."</th>\n";
		echo "<th>"._ADMIN_MEMBERS_GROUP_MEMBERS."</th>\n";
		echo "<th>"._ADMIN_ACTIONS."</th>\n";
		echo "</tr>\n";
		while ($row = db::fetchObject($sql)) {
			// first group?
			if ($row->id == 1) {
				echo "<tr class='disabled'>\n";
			} else {
				echo "<tr>\n";
			}
			echo "<td width='60%'><a href='index.php?action=members&amp;group=".$row->id."'>".$row->name."</a></td>\n";
			echo "<td width='25%' class='center'>".$this->countGroupMembersById($row->id)."</td>\n";
			echo "<td width='15%' class='center'>\n";
			if ($row->id == '1') {
				echo "-\n";
			} else {
				echo "<a href='index.php?action=members&amp;page=editgroup&amp;id=".$row->id."'>".Admin::image('group_edit',_ADMIN_MEMBERS_GROUP_EDIT)."</a>\n";
				echo "<a href='index.php?action=members&amp;page=deletegroup&amp;id=".$row->id."'>".Admin::image('group_delete',_ADMIN_MEMBERS_GROUP_DELETE)."</a>\n";
			}
			echo "</td>\n";
			echo "</tr>\n";
		}
		echo "</table>\n";
		db::free($sql);
		
		Admin::footer();
	}
}
